
use std::error::Error;
use std::thread;
use std::net::{TcpListener, TcpStream};
use std::io::{self, Write, Read};
use std::sync::{mpsc, mpsc::{Receiver, Sender}};
use icc_server::{IccParam, icc_deal::{icc_rsp, icc_req}};

pub fn handle_client(param: IccParam) -> Result<(), Box<dyn Error>> 
{
    // 监听指定的 IP 和端口
    let addr = format!("{}:{}", param.ip, param.ue_port);
    println!("Server listening on {}", addr);
    let listener = TcpListener::bind(&addr)?;
    let mut handler = vec![];

    for stream in listener.incoming() {
        let (tx, rx) = mpsc::channel();
        match stream {
            Ok(stream) => {
                println!("new {} connection to {}", stream.peer_addr().unwrap(), addr);
                let param1 = param.clone();
                let param2 = param.clone();
                let stream1 = stream.try_clone()?;

                handler.push(thread::spawn(move || {
                    server_request_deal(stream1, param2, rx);
                }));

                connect_deal(param1, stream, tx);
            }
            Err(e) => {
                eprintln!("Error on {}: {}", addr, e);
            }
        }
    }

    //线程回收
    for i in handler {
        i.join().unwrap();
    }
    Ok(())
}

fn connect_deal(param: IccParam, mut stream: TcpStream, tx: Sender<u32>)
{
    tx.send(104).unwrap();  //ue连接成功主发送104

    // 读取客户端发送的数据
    let mut buffer = [0; 4096];
    loop {
        buffer.fill(0); //接收前清空
        let result = stream.read(&mut buffer);
        let rcv_len = match result {
            Ok(n) => {
                if n == 0 {
                    println!("Client disconnected");
                    return;
                }
                n
            }
            Err(e) => {
                eprintln!("Error reading from stream: {}", e);
                return;
            }
        };

        // 处理客户端发送的数据
        println!("ue rcv: {}", String::from_utf8_lossy(&buffer[..rcv_len]));

        let json_str = std::str::from_utf8(&buffer[..rcv_len]).unwrap_or_else(|err| {
            eprintln!("Error converting buffer to UTF-8, err inof:{}", err);
            return "";
        });
        let json_value: serde_json::Value = serde_json::from_str(json_str).unwrap_or_else(|err| {
            eprintln!("Error parsing JSON, err info:{}", err);
            return serde_json::Value::Null;
        });

        buffer.fill(0); //发送前清空
        let event = json_value["event"].as_u64().unwrap() as u32;
        let len = match event {
            1|2|3|4|5|6|7|8|9|10|11|12|14|15|16|17|18|19|21 => {
                let data = icc_rsp::universal(event);
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()
            }
            20 => {
                let data = icc_rsp::event20(param.ustate);
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()
            }
            1101..1105 => {
                //客户端的应答，不需要处理
                println!("recv {} event.", event);
                continue;
            }
            _ => {
                let data = "Not yet supported...".to_string();
                buffer[..data.len()].copy_from_slice(data.as_bytes());
                data.len()
            }
        };

        // 发送响应数据
        stream.write_all(&buffer[..len]).unwrap_or_else(|err| {
            eprintln!("Error writing to stream: {}", err);
        });

        if event == 2 || event == 5 {
            tx.send(event).unwrap();
        }
    }
}

fn server_request_deal(mut stream: TcpStream, param: IccParam, rx: Receiver<u32>)
{
    let mut buffer = String::new();
    loop {
        let event = rx.recv().unwrap();
        if event == 2 {
            match event101_pack() {
                Ok(tmp_buf) => {
                    buffer = tmp_buf;
                },
                Err(err) => {
                    eprintln!("Error in event101_pack: {}", err);
                    continue;
                }
            }
        } else if event == 104 {
            buffer = icc_req::event104(param.dstate, param.ustate, param.vstate, param.ueupver.as_str());
        } else if event == 5 {
            match event102_pack() {
                Ok(tmp_buf) => {
                    buffer = tmp_buf;
                },
                Err(err) => {
                    eprintln!("Error in event102_pack: {}", err);
                    continue;
                }
            }
        }

        if !buffer.is_empty() {
            println!("up send: {}", buffer);
            // 发送响应数据
            let len = buffer.len();
            stream.write_all(buffer[..len].as_bytes()).unwrap_or_else(|err| {
                eprintln!("Error writing to stream: {}", err);
            });
            buffer.clear();
        }
    }
}

fn event101_pack() -> Result<String, Box<dyn Error>> 
{
    println!("下载授权请求, 请输入: 0 允许下载 1 取消下载");
    // loop {
    //     //获取用户在终端上输入的值
    //     let mut input = String::new();
    //     io::stdin().read_line(&mut input)?;
    //     let dvalue = match input.trim().parse::<u8>() {
    //         Ok(num) => num,
    //         Err(_) => {
    //             println!("Invalid input. 请输入: 0 允许下载 1 取消下载");
    //             continue;
    //         }
    //     };
    //     let dvalue = !!dvalue;
    //     let buf = icc_req::event101(dvalue);
    //     return Ok(buf);
    // }

    //默认允许下载
    let buf = icc_req::event101(0);
    return Ok(buf);
}

fn event102_pack() -> Result<String, Box<dyn Error>> 
{
    println!("升级授权请求, 请输入格式为: 0 1 08:30
    第一个参数: 0立即升级 1预约升级
    第二个参数: 0允许升级 1取消升级 2推迟升级 3前置条件检查
    第三个参数: 预约升级的时间, eg 08:30");
    // loop {
    //     let mut input = String::new();
    //     io::stdin().read_line(&mut input)?;
    //     //按空格分割输入
    //     let parts: Vec<&str> = input.trim().split_whitespace().collect();
    //     if parts.len() != 3 {
    //         println!("Invalid input, 请输入三个参数，如: 0 1 08:30");
    //         continue;
    //     }
    //     let u_type = match parts[0].parse::<u8>() {
    //         Ok(num) => num,
    //         Err(_) => {
    //             println!("第一个参数无效，请输入一个有效的 u8 数值");
    //             continue;
    //         }
    //     };
    //     let u_value = match parts[1].parse::<u8>() {
    //         Ok(num) => num,
    //         Err(_) => {
    //             println!("第二个参数无效，请输入一个有效的 u8 数值");
    //             continue;
    //         }
    //     };
    //     let u_time = parts[2];
    //     let buf = icc_req::event102(u_type, u_value, u_time);
    //     return Ok(buf);
    // }

    //默认立即升级
    let buf = icc_req::event102(0, 3, "08:30");
    return Ok(buf);
}